


// Author:					HungNM
// Created:					16-08-2012
// Last Modified:			16-08-2012
//
	
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using eProject.Data;
	
namespace eProject.Business
{
	
	public class Users
	{

		#region Constructors

	    public Users()
		{}
	    
	
	    public Users(long id) 
		{
	        GetUsers(id); 
	    }

        public Users(string userName) 
		{
            CheckForLogin(userName); 
	    }

		#endregion

		#region Private Properties

		private long id;
		private string userName = string.Empty;
		private string password = string.Empty;
		private string challengeCode = string.Empty;
		private string email = string.Empty;
		private int roles = -1;
		private string firstName = string.Empty;
        private string lastName = string.Empty;
		private DateTime dateOfBirth;
		private bool gender = false;
		private string address = string.Empty;
		private string phoneNumber = string.Empty;
		private long distance;
		private bool isApproved = false;
		private bool isBlocked = false;
		private bool isDeleted = false;
		private Guid activationCode = Guid.Empty;
		private DateTime activationTime = DateTime.UtcNow;
		private DateTime createdDate = DateTime.UtcNow;
		private DateTime lastUpdate = DateTime.UtcNow;
        private List<Permissions> listPermistions = null;
		
		#endregion

		#region Public Properties

		public long Id 
		{
			get { return id; }
			set { id = value; }
		}
		public string UserName 
		{
			get { return userName; }
			set { userName = value; }
		}
		public string Password 
		{
			get { return password; }
			set { password = value; }
		}
		public string ChallengeCode 
		{
			get { return challengeCode; }
			set { challengeCode = value; }
		}
		public string Email 
		{
			get { return email; }
			set { email = value; }
		}
		public int Roles 
		{
			get { return roles; }
			set { roles = value; }
		}
		public string FirstName 
		{
			get { return firstName; }
            set { firstName = value; }
		}
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
		public DateTime DateOfBirth 
		{
			get { return dateOfBirth; }
			set { dateOfBirth = value; }
		}
		public bool Gender 
		{
			get { return gender; }
			set { gender = value; }
		}
		public string Address 
		{
			get { return address; }
			set { address = value; }
		}
		public string PhoneNumber 
		{
			get { return phoneNumber; }
			set { phoneNumber = value; }
		}
		public long Distance 
		{
			get { return distance; }
			set { distance = value; }
		}
		public bool IsApproved 
		{
			get { return isApproved; }
			set { isApproved = value; }
		}
		public bool IsBlocked 
		{
			get { return isBlocked; }
			set { isBlocked = value; }
		}
		public bool IsDeleted 
		{
			get { return isDeleted; }
			set { isDeleted = value; }
		}
		public Guid ActivationCode 
		{
			get { return activationCode; }
			set { activationCode = value; }
		}
		public DateTime ActivationTime 
		{
			get { return activationTime; }
			set { activationTime = value; }
		}
		public DateTime CreatedDate 
		{
			get { return createdDate; }
			set { createdDate = value; }
		}
		public DateTime LastUpdate 
		{
			get { return lastUpdate; }
			set { lastUpdate = value; }
		}
        public List<Permissions> ListPermistions
        {
            get { return listPermistions; }
            set { listPermistions = value; }
        }

		#endregion

		#region Private Methods

		/// <summary>
		/// Gets an instance of Users.
		/// </summary>
		/// <param name="id"> id </param>
		private void GetUsers(long id) 
		{
			try
			{
				using(IDataReader reader = DBUsers.GetOne(id)) 
				{
					PopulateFromReader(reader);
				}
			}
			catch(Exception ex)
			{
				throw ex;
			}
		}
		
		
		private void PopulateFromReader(IDataReader reader) 
		{
			try
			{
				if(reader.Read())
				{
                    this.id = Convert.ToInt64(reader["Id"]);
                    this.userName = reader["UserName"].ToString();
                    this.password = reader["Password"].ToString();
                    this.challengeCode = reader["ChallengeCode"].ToString();
                    this.email = reader["Email"].ToString();
                    if (!string.IsNullOrEmpty(reader["Roles"].ToString()))
                        this.roles = Convert.ToInt32(reader["Roles"]);
                    this.firstName = reader["firstName"].ToString();
                    this.lastName = reader["lastName"].ToString();
                    if (!string.IsNullOrEmpty(reader["DateOfBirth"].ToString()))
                        this.dateOfBirth = Convert.ToDateTime(reader["DateOfBirth"]);
                    if (!string.IsNullOrEmpty(reader["Gender"].ToString()))
                        this.gender = Convert.ToBoolean(reader["Gender"]);
                    this.address = reader["Address"].ToString();
                    this.phoneNumber = reader["PhoneNumber"].ToString();
                    if (!string.IsNullOrEmpty(reader["Distance"].ToString()))
                        this.distance = Convert.ToInt64(reader["Distance"]);
                    if (!string.IsNullOrEmpty(reader["IsApproved"].ToString()))
                        this.isApproved = Convert.ToBoolean(reader["IsApproved"]);
                    if (!string.IsNullOrEmpty(reader["IsBlocked"].ToString()))
                        this.isBlocked = Convert.ToBoolean(reader["IsBlocked"]);
                    if (!string.IsNullOrEmpty(reader["IsDeleted"].ToString()))
                        this.isDeleted = Convert.ToBoolean(reader["IsDeleted"]);
                    if (!string.IsNullOrEmpty(reader["ActivationCode"].ToString()))
                        this.activationCode = new Guid(reader["ActivationCode"].ToString());
                    if (!string.IsNullOrEmpty(reader["ActivationTime"].ToString()))
                        this.activationTime = Convert.ToDateTime(reader["ActivationTime"]);
                    if (!string.IsNullOrEmpty(reader["CreatedDate"].ToString()))
                        this.createdDate = Convert.ToDateTime(reader["CreatedDate"]);
                    if (!string.IsNullOrEmpty(reader["LastUpdate"].ToString()))
                        this.lastUpdate = Convert.ToDateTime(reader["LastUpdate"]);
                    this.listPermistions = Permissions.GetAll(this.roles);
				
				}
			}
			catch(Exception ex)
			{
				throw ex;
			}
		}
		
		/// <summary>
        /// Persists a new instance of Users. Returns true on success.
        /// </summary>
        /// <returns></returns>
		private bool Create()
		{ 
			int newID = 0;
            this.challengeCode = EncryptHelper.RandomString(10, false);
            this.password = EncryptHelper.Encrypt(this.password, this.challengeCode, true);
            this.activationCode = Guid.NewGuid();

			try
			{
				newID = DBUsers.Create(
					this.userName, 
					this.password, 
					this.challengeCode, 
					this.email, 
					this.roles, 
					this.firstName, 
                    this.lastName,
					this.dateOfBirth, 
					this.gender, 
					this.address, 
					this.phoneNumber, 
					this.distance, 
					this.isApproved, 
					this.isBlocked, 
					this.isDeleted, 
					this.activationCode, 
					this.activationTime, 
					this.createdDate, 
					this.lastUpdate); 
					
				this.id = newID;
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return (newID > 0);
		}

		
		/// <summary>
        /// Updates this instance of Users. Returns true on success.
        /// </summary>
        /// <returns>bool</returns>
		private bool Update()
		{
			bool IsUpdated = false;
			try
			{
                this.lastUpdate = DateTime.UtcNow;

				IsUpdated = DBUsers.Update(
					this.id, 
					this.userName, 
					this.password, 
					this.challengeCode, 
					this.email, 
					this.roles,
                    this.firstName,
                    this.lastName,
					this.dateOfBirth, 
					this.gender, 
					this.address, 
					this.phoneNumber, 
					this.distance, 
					this.isApproved, 
					this.isBlocked, 
					this.isDeleted, 
					this.activationCode, 
					this.activationTime, 
					this.createdDate, 
					this.lastUpdate); 
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return IsUpdated;
		}

		#endregion

		#region Public Methods

		/// <summary>
        /// Saves this instance of Users. Returns true on success.
        /// </summary>
        /// <returns>bool</returns>
		public bool Save()
		{
			bool IsSaved = false;
			try
			{
				if(this.id > 0)
				{
					IsSaved = Update();
				}
				else
				{
					IsSaved = Create();
				}
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return IsSaved;
		}
		
		#endregion

		#region Static Methods

		/// <summary>
		/// Deletes an instance of Users. Returns true on success.
		/// </summary>
		/// <param name="id"> id </param>
		/// <returns>bool</returns>
        public static bool Delete(long id, bool isDeleted) 
		{
			bool IsDeleted = false;
			try
			{
				IsDeleted = DBUsers.Delete(id, isDeleted); 
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return IsDeleted;
		}

        /// <summary>
        /// Check user an instance of Users. Returns true on success.
        /// </summary>
        /// <param name="id"> id </param>
        /// <returns>bool</returns>
        public static bool CheckUser(string userName)
        {
            bool IsValid = false;
            try
            {
                IsValid = DBUsers.CheckUser(userName);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return IsValid;
        }

        /// <summary>
        /// Check user an instance of Users. Returns true on success.
        /// </summary>
        /// <param name="id"> id </param>
        /// <returns>bool</returns>
        private void CheckForLogin(string userName)
        {
            try
            {
                using (IDataReader reader = DBUsers.CheckForLogin(userName))
                {
                    PopulateFromReader(reader);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
		
		
		/// <summary>
		/// Gets a count of Users. 
		/// </summary>
		public static int GetCount()
		{
			int count = 0;
			try
			{
				count = DBUsers.GetCount();
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return count;
		}
	
		private static List<Users> LoadListFromReader(IDataReader reader)
		{
			List<Users> usersList = new List<Users>();
			try
			{
				while (reader.Read())
				{
					Users users = new Users();
					users.id = Convert.ToInt64(reader["Id"]);
					users.userName = reader["UserName"].ToString();
					users.password = reader["Password"].ToString();
					users.challengeCode = reader["ChallengeCode"].ToString();
					users.email = reader["Email"].ToString();
                    if (!string.IsNullOrEmpty(reader["Roles"].ToString()))
					    users.roles = Convert.ToInt32(reader["Roles"]);
                    users.firstName = reader["FirstName"].ToString();
                    users.lastName = reader["LastName"].ToString();
                    if (!string.IsNullOrEmpty(reader["DateOfBirth"].ToString()))
					    users.dateOfBirth = Convert.ToDateTime(reader["DateOfBirth"]);
                    if (!string.IsNullOrEmpty(reader["Gender"].ToString()))
					    users.gender = Convert.ToBoolean(reader["Gender"]);
					users.address = reader["Address"].ToString();
					users.phoneNumber = reader["PhoneNumber"].ToString();
                    if (!string.IsNullOrEmpty(reader["Distance"].ToString()))
					    users.distance = Convert.ToInt64(reader["Distance"]);
                    if (!string.IsNullOrEmpty(reader["IsApproved"].ToString()))
					    users.isApproved = Convert.ToBoolean(reader["IsApproved"]);
                    if (!string.IsNullOrEmpty(reader["IsBlocked"].ToString()))
					    users.isBlocked = Convert.ToBoolean(reader["IsBlocked"]);
                    if (!string.IsNullOrEmpty(reader["IsDeleted"].ToString()))
					    users.isDeleted = Convert.ToBoolean(reader["IsDeleted"]);
                    if (!string.IsNullOrEmpty(reader["ActivationCode"].ToString()))
					    users.activationCode = new Guid(reader["ActivationCode"].ToString());
                    if (!string.IsNullOrEmpty(reader["ActivationTime"].ToString()))
					    users.activationTime = Convert.ToDateTime(reader["ActivationTime"]);
                    if (!string.IsNullOrEmpty(reader["CreatedDate"].ToString()))
					    users.createdDate = Convert.ToDateTime(reader["CreatedDate"]);
                    if (!string.IsNullOrEmpty(reader["LastUpdate"].ToString()))
					    users.lastUpdate = Convert.ToDateTime(reader["LastUpdate"]);
                    users.listPermistions = Permissions.GetAll(users.roles);
					usersList.Add(users);
					
				}
			}
			finally
			{
				reader.Close();
			}
	
			return usersList;
		}
	
		/// <summary>
		/// Gets an IList with all instances of Users.
		/// </summary>
		public static List<Users> GetAll()
		{
			List<Users> listUsers = new List<Users>();
			try
			{
				IDataReader reader = DBUsers.GetAll();
				listUsers = LoadListFromReader(reader);
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return listUsers;
		}

        /// <summary>
        /// Gets an IList with all instances of Users.
        /// </summary>
        public static List<Users> GetAllWithSearchText(string searchText, bool isDeleted)
        {
            List<Users> listUsers = new List<Users>();
            try
            {
                IDataReader reader = DBUsers.GetAllWithSearchText(searchText, isDeleted);
                listUsers = LoadListFromReader(reader);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return listUsers;
        }
	
		/// <summary>
		/// Gets an IList with page of instances of Users.
		/// </summary>
		/// <param name="pageNumber">The page number.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="totalPages">total pages</param>
		public static List<Users> GetPage(int pageNumber, int pageSize, out int totalPages)
		{
			totalPages = 1;
			List<Users> listUsers = new List<Users>();
			try
			{
				IDataReader reader = DBUsers.GetPage(pageNumber, pageSize, out totalPages);	
				listUsers = LoadListFromReader(reader);
			}
			catch(Exception ex)
			{
				throw ex;
			}
			
			return listUsers;
		}
		
		#endregion

	}
}





